package com.example.app15_handler.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.app15_handler.R;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 测试Handler的基本使用
 * 1、创建Handler成员变量对象，并重写其HandleMessage方法
 * 2、在分/主线程创建Message对象
 * 3、使用handler对象发送Message
 * 4、在handleMessage()中处理消息
 */
public class TestHandlerActivity extends AppCompatActivity {

    private static final String TAG = "HandlerDemoActivity";

    private ProgressBar pbHandlerLoading;

    private EditText etHandlerResult;

    /**
     * 定义Handler成员变量
     */
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            // 处理消息
            if (msg.what == 1) {
                String result = msg.obj.toString();
                etHandlerResult.setText(result);
                pbHandlerLoading.setVisibility(View.INVISIBLE);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_handler_test);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        Log.i(TAG, "onCreate()");

        pbHandlerLoading = findViewById(R.id.pb_handler_loading);
        etHandlerResult = findViewById(R.id.et_handler_result);
    }

    /**
     * 按钮点击事件
     * @param view view
     */
    public void getSubmit1(View view) {
        // 主线程显示提示视图
        pbHandlerLoading.setVisibility(View.VISIBLE);
        // 分线程，发送网络请求
        new Thread(() -> {
            //  String path = "http://10.189.124.52:8080/getUserInfo?name=John&age=60";
            String path = "http://192.168.3.12:8080/getUserInfo?name=John&age=60";
            String result = requestToString(path);
            // 主线程显示数据
            runOnUiThread(() -> {
                etHandlerResult.setText(result);
                pbHandlerLoading.setVisibility(View.INVISIBLE);
            });
        }).start();
    }

    /**
     * 按钮点击事件
     * @param view view
     */
    public void getSubmit2(View view) {
        // 主线程显示提示视图
        pbHandlerLoading.setVisibility(View.VISIBLE);
        // 分线程，发送网络请求
        new Thread(() -> {
            //  String path = "http://10.189.124.52:8080/getUserInfo?name=John&age=60";
            String path = "http://192.168.3.12:8080/getUserInfo?name=John&age=60";
            String result = requestToString(path);
            // 主线程显示数据
            // 在分/主线程创建Message对象
            Message message = Message.obtain();
            // 设置标识
            message.what = 1;
            message.obj = result;
            // 使用handler对象发送消息
            handler.sendMessage(message);
        }).start();
    }

    private String requestToString(String path) {
        try {
            URL url = new URL(path);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            // 打开连接
            connection.connect();
            String result;
            try (InputStream in = connection.getInputStream();
                 ByteArrayOutputStream out = new ByteArrayOutputStream()) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = in.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                    Thread.sleep(10);
                }
                result = out.toString();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            connection.disconnect();
            return result;
        } catch (IOException e) {
            // 隐藏loading进度条
            pbHandlerLoading.setVisibility(View.INVISIBLE);
            Log.e(TAG, "requestToString: " + e.getMessage(), e);
            Thread.currentThread().interrupt();
        }
        return null;
    }
}